package com.mate.utils;

import org.apache.http.*;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.ssl.TrustStrategy;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;
import java.security.cert.X509Certificate;
import java.util.List;
import java.util.Map;

public class HttpsUtils {

    protected static List<NameValuePair> params;

    private static Logger logger = LoggerFactory.getLogger(HttpsUtils.class);

    static CloseableHttpClient httpClient;

    static CloseableHttpResponse httpResponse;

    private static CloseableHttpClient createSSLClientDefault() {
        try {
            SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
                public boolean isTrusted(X509Certificate[] chain, String authType) {
                    return true;
                }
            }).build();
            HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE;
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
            return HttpClients.custom().setSSLSocketFactory(sslsf).build();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return HttpClients.createDefault();
    }

    public static String doGet(String url) throws IOException {
        String result = null;
        CloseableHttpClient httpclient = null;
        try {
            httpclient = HttpClients.createDefault();
            HttpGet httpGet = new HttpGet(url);
            httpGet.setHeader("Cookie", " _lxsdk_cuid=171f2645d059e-06289612abb27c-b363e65-1fa400-171f2645d07c8; uuid_n_v=v1; iuuid=F1B0647090DE11EAB8825B7772488A8548F6A50A13A24E01981BA9FE464D5198; webp=true; ci=89%2C%E5%B8%B8%E5%B7%9E; selectci=; Hm_lvt_703e94591e87be68cc8da0da7cbd0be2=1588909613,1588919360; _lx_utm=utm_source%3DBaidu%26utm_medium%3Dorganic; __mta=208007725.1588909612881.1588909751947.1588919359852.8; _lxsdk=F1B0647090DE11EAB8825B7772488A8548F6A50A13A24E01981BA9FE464D5198; _last_page=c_dmLad; Hm_lpvt_703e94591e87be68cc8da0da7cbd0be2=1588924593; _lxsdk_s=171f2f958d7-a56-d7b-b6a%7C%7C267; __mta=208007725.1588909612881.1588919359852.1588924593533.9");
            httpGet.setHeader("User-Agent", "Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1");
            HttpResponse response = httpclient.execute(httpGet);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == HttpStatus.SC_OK) {
                result = EntityUtils.toString(response.getEntity(), "utf-8");
            } else {
                logger.error("请求异常代码:::" + statusCode);
            }
        } catch (IOException e) {
            logger.error(e.getMessage());
        } finally {
            if (httpclient != null) {
                httpclient.close();
            }
        }
        return result;
    }

    public static String doPostJson(String url, String json) throws IOException {
        String result = null;
        CloseableHttpClient httpclient = null;
        try {
            httpclient = HttpClients.createDefault();
            HttpPost httpPost = new HttpPost(url);
            httpPost.setHeader("Accept", "application/json");
            httpPost.addHeader("Content-type", "application/json; charset=utf-8");
            httpPost.setEntity(new StringEntity(json, Charset.forName("UTF-8")));
            HttpResponse response = httpclient.execute(httpPost);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == HttpStatus.SC_OK) {
                result = EntityUtils.toString(response.getEntity(), "utf-8");
            }
            httpclient.close();
        } catch (IOException e) {
            logger.error(e.getMessage());
        } finally {
            if (httpclient != null) {
                httpclient.close();
            }
        }
        return result;
    }

    /**
     * 发送https请求
     */
    public static String sendByHttp(Map<String, Object> params, String url) {
        try {
            HttpPost httpPost = new HttpPost(url);
            httpClient = HttpsUtils.createSSLClientDefault();
            httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            if (httpEntity != null) {
                String jsObject = EntityUtils.toString(httpEntity, "UTF-8");
                return jsObject;
            } else {
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            try {
                httpResponse.close();
                httpClient.close();
                logger.info("请求流关闭完成");
            } catch (IOException e) {
                logger.info("请求流关闭出错");
                e.printStackTrace();
            }
        }
    }

}
